<?php

namespace app\controller\teacher;

use app\BaseController;
use app\Code;
use app\dao\ResourceDao;
use app\validate\ResourceValidate;
use think\exception\ValidateException;
use think\facade\Request;
use think\facade\Filesystem;
use think\facade\Log;

class ResourceController extends BaseController
{
    // 上传资源
    public function upload()
    {
        $data = Request::post();

        try {
            validate(ResourceValidate::class)->scene('upload')->check($data);
        } catch (ValidateException $e) {
            return $this->returnJson([], Code::UNPROCESSABLE_ENTITY, $e->getMessage());
        }

        $file = Request::file('file');

        // 文件类型验证
        $allowedTypes = [
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        ];
        if (!in_array($file->getMimeType(), $allowedTypes)) {
            return $this->returnJson([], Code::BAD_REQUEST, '文件类型不支持');
        }

        try {
            validate(ResourceValidate::class)
                ->scene('upload')
                ->check([
                    'file' => $file,
                    'description' => $data['description'] ?? ''
                ]);

            $savename = Filesystem::disk('public')->putFile('resources', $file);
            $filePath = '/storage/' . $savename;

            $result = ResourceDao::saveResource($teacherId, $filePath, $data['description'] ?? '');

            return $this->returnJson();
        } catch (ValidateException $e) {
            return $this->returnJson([], Code::BAD_REQUEST, $e->getMessage());
        } catch (\Exception $e) {
            Log::error("上传资源失败: " . $e->getMessage());
            return $this->returnJson([], Code::SERVER_ERROR, '服务器错误，请稍后再试');
        }
    }
}
